package com.zxd.interview.cocurrent;

import java.io.FilePermission;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;

/**
 * 特权访问理解
 *
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.cocurrent
 * @Description : 特权访问理解
 * @Create on : 2023/7/12 11:28
 **/
public class doPrivilegedTest {

    public void doService() {

//        doFileOperation();

        // 经过改写之后顺利获取权限
        AccessController.doPrivileged((PrivilegedAction) () -> {
            doFileOperation();
            return null;
        });
    }



    private void doFileOperation() {
        // 通常情况下会抛出权限错误
        Permission perm = new FilePermission("C:/text.txt", "read");
        AccessController.checkPermission(perm);
        System.out.println("TestService has permission");
    }

    public void loadService() {
        URL[] urls;
        try {
            urls = new URL[] { new URL("file:C:/text.txt") };
            URLClassLoader ll = new URLClassLoader(urls);
            final Class a = ll.loadClass("com.zxd.interview.cocurrent.doPrivilegedTest");
            Object o = a.newInstance();
            Method m = a.getMethod("doService", null);
            m.invoke(o, null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        doPrivilegedTest s = new doPrivilegedTest();
        s.loadService();
    }
}
